<?php

namespace App\Http\Controllers\Backstage\Encyclopedia;

use App\Http\Controllers\BaseController;
use App\Http\Requests\Backstage\Encyclopedia\Article\CreateRequest;
use App\Http\Requests\Backstage\Encyclopedia\Article\UpdateRequest;
use App\Models\Encyclopedia\Article;
use App\Models\Encyclopedia\ArticleContent;
use App\Transformers\Encyclopedia\ArticleTransformer;
use Illuminate\Http\Request;

class ArticleController extends BaseController
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $page_size = get_request_page();
        $articles = Article::paginate($page_size);
        return $this->response->paginator($articles, new ArticleTransformer());
    }

    /**
     * Store a newly created resource in storage.
     * @param CreateRequest $request
     * @throws \Throwable
     */
    public function store(CreateRequest $request)
    {
        $model = \DB::transaction(function () use ($request) {
            $attributes = $request->validated();
            $article = Article::create(array_merge($attributes, ['author_id' => \Auth::user()->id]));
            ArticleContent::create([
                'article_id' => $article->id, 'content' => array_get($attributes, 'content')
            ]);
            return $article;
        });
    }

    public function show($id)
    {
        $model = Article::find($id);
        return $this->response->item($model, new ArticleTransformer());
    }

    /**
     * @param UpdateRequest $request
     * @param $id
     * @throws \Throwable
     */
    public function update(UpdateRequest $request, $id)
    {
        \DB::transaction(function () use ($request, $id) {
            $attributes = $request->validated();
            $article = Article::with('content')->find($id);
            $model = $article->update($attributes);
            $content = $article->content;
            $content->content = array_get($attributes, 'content');
            $content->save();
            return $model;
        });
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}
